package com.chens.modules.content.controller;

import com.chens.common.controller.BaseController;
import com.chens.modules.content.model.Post;
import com.chens.payload.ApiResponse;
import com.chens.modules.content.service.PostService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/content/posts")
public class PostController extends BaseController {

    @Autowired
    private PostService postService;

    @GetMapping
    public ApiResponse<Page<Post>> getPosts(@RequestParam(defaultValue = "0") int page,
                                            @RequestParam(defaultValue = "10") int size) {
        return ApiResponse.success(postService.getPosts(page, size));
    }

    @GetMapping("/{id}")
    public ApiResponse<Post> getPostById(@PathVariable Long id) {
        Optional<Post> optional = postService.getPostById(id);
        return optional.map(ApiResponse::success).orElseGet(
                () -> ApiResponse.error(200, "Post not found with id " + id));
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<Post> createPost(@RequestBody Post post, HttpServletRequest request) {
        // 从请求中获取当前用户名
        post.setAuthor(getCurrentUsername(request));
        // 设置创建时间
        return ApiResponse.success(postService.createPost(post));
    }

    @PutMapping("/{id}")
    public ApiResponse<Post> updatePost(@PathVariable Long id, @RequestBody Post postDetails) {
        try {
            Post updatedPost = postService.updatePost(id, postDetails);
            return ApiResponse.success(updatedPost);
        } catch (RuntimeException e) {
            return ApiResponse.error(200, "Post not found with id " + id);
        }
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deletePost(@PathVariable Long id) {
        postService.deletePost(id);
        return ApiResponse.success(null);
    }
}